<?php
declare(strict_types=1);

namespace lib\pay;


class PayBase extends \sys\Data {
    use \lib\data\traits\WaitLock;

    const STAGE_PAYING          = 0;    # 支付中|等待支付
    const STAGE_PAID            = 1;    # 支付成功
    const STAGE_CLOSED          = 2;    # 交易关闭 支付失败
    const STAGE_ERROR           = 3;    # 系统出错
    const STAGE_FINISHED        = 4;    # 锁定了 无需再次操作 。
    const STAGE_REFUND          = 5;    # 已退款
    const STAGE_FAILED          = 6;    # 支付失败
    const STAGE_REFUND_ERROR    = 7;    # 退款出错.

    protected static array $micropay_cached     = [];
    protected static array $qrcodepay_cached    = [];
    protected static array $notify_inprogress   = [];

    public static function createInstance(array $data, bool $reload = false) : static {
        return new static($data);
    }

    # 取消支付
    public static function micropay_cancel(string $auth_code, string $ipaddr) : bool
    {
        if(isset(static::$micropay_cached[$auth_code])){
            list($pay, $channel) = static::$micropay_cached[$auth_code];
            $pay->lock();
            if($pay->stage == static::STAGE_PAYING){
                $result = $pay->cancel($ipaddr);
            }
            $channel->push(true);
            $pay->unlock();
            return $result;
        }
        return false;
    }

    # 二维码支付. 取消支付
    public static function qrcodepay_cancel(string $out_trade_no) :bool {
        if(null !== ($channel = (static::$qrcodepay_cached[$out_trade_no] ?? null))){
            unset(static::$qrcodepay_cached[$out_trade_no]);
            $channel->push(false);
            if(empty(static::$qrcodepay_cached)){
                static::$qrcodepay_cached = [];
            }
            return true;
        }
        return false;
    }
}